/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Engine2D.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Garys
 */
public class ClientConnection implements Connection<Socket> {

    /**
     *
     */
    protected Socket socket = null;
    private Protocol protocol = null;
    private final InetAddress serverIP;
    private final int serverPort;
    private DataInputStream fromServer;
    private DataOutputStream toServer;

    /**
     *
     */
    protected ClientConnection() {
        this.serverIP = null;
        this.serverPort = -1;
    }

    /**
     * 
     * @param args
     * @throws UnknownHostException
     */
    public static void main(String[] args) throws UnknownHostException {

        for (int i = 0; i < 10000; i++) {

            Thread connector = new Thread() {

                @Override
                public void run() {
                    ClientConnection client = null;
                    try {
                        client = new ClientConnection(InetAddress.getByName("192.168.1.64"), 8000);
                    } catch (UnknownHostException ex) {
                        Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                    client.connect();
                    while (true) {
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }
            };
            connector.start();
            System.out.println(i);
            try {
                Thread.sleep(30);
            } catch (InterruptedException ex) {
                Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    }

    /**
     *
     * @param serverIP
     * @param serverPort
     */
    public ClientConnection(InetAddress serverIP, int serverPort) {

        this.serverIP = serverIP;
        this.serverPort = serverPort;

    }

    /**
     *
     * @return
     */
    @Override
    public synchronized boolean connect() {
        try {
            // Create a socket to connect to the server
            socket = new Socket(serverIP, serverPort);

            return socket.isConnected();

        } catch (IOException ex) {

            return false;
        }

    }

    /**
     *
     * @return
     */
    @Override
    public boolean disconnect() {

        if (!isConnected()) {
            return true;
        }


        try {

            if (getSocket() != null) {
                getSocket().close();
            }
        } catch (IOException ex) {
        }

        return !isConnected();


    }

    /**
     *
     * @return
     */
    @Override
    public boolean isConnected() {
        if (getSocket() != null) {
            return getSocket().isConnected() && !getSocket().isClosed();
        }
        return false;
    }

    /**
     *
     * @return
     */
    @Override
    public Socket getSocket() {
        return socket;
    }

    /**
     *
     * @return
     */
    @Override
    public InetAddress getLocalIP() {
        if (getSocket() != null) {
            return getSocket().getLocalAddress();
        }
        return null;
    }

    /**
     *
     * @return
     */
    @Override
    public InetAddress getRemoteIP() {
        if (getSocket() != null) {
            return getSocket().getInetAddress();
        }
        return null;
    }

    /**
     *
     * @return
     */
    public int getLocalPort() {
        if (getSocket() != null) {
            return getSocket().getLocalPort();
        }
        return -1;
    }

    /**
     * @return the communication port of the server
     */
    public int getRemotePort() {
        if (getSocket() != null) {
            return getSocket().getPort();
        }
        return serverPort;
    }

    /**
     *
     * @return
     */
    @Override
    public boolean isServer() {
        return false;
    }

    /**
     *
     * @param data
     * @return
     * @throws IOException
     */
    public int send(String data) throws IOException {

        toServer = new DataOutputStream(getSocket().getOutputStream());
        toServer.writeUTF(data);
        toServer.flush();

        return data.length();

    }

    /**
     *
     * @return
     */
    public int hasInput() {
        if (getSocket() == null) {
            return -1;
        }
        try {
            return getSocket().getInputStream().available();
        } catch (IOException e) {
            return -1;
        }
    }

    /**
     *
     * @return @throws IOException 
     * @throws IOException
     */
    public String readInput() throws IOException {
        if (getSocket() == null) {

            throw new IOException();
        }

        fromServer = new DataInputStream(getSocket().getInputStream());


        return fromServer.readUTF();


    }

    /**
     *
     * @throws IOException
     */
    public void checkInput() throws IOException {
        if (getProtocol() == null) {

            return;

        }
        if (getSocket() != null) {

            fromServer = new DataInputStream(getSocket().getInputStream());
            if (fromServer.available() > 0) {

                //There is some problem synchronizing in few case when using JOptionPane (blocking) ...
                synchronized (getProtocol()) {

                    //Process input if protocol exist
                    getProtocol().processInput(fromServer);
                }
            }
        }

    }

    /**
     *
     * @param message
     * @param sendAll
     */
    public void processOutput(String message, boolean sendAll) {
        if (getProtocol() == null) {

            return;

        }

        synchronized (getProtocol()) {

            getProtocol().processOutput(message, sendAll);
        }

    }

    /**
     *
     * @return
     */
    public Protocol getProtocol() {
        return protocol;
    }

    /**
     *
     * @param protocol
     */
    public void setProtocol(Protocol protocol) {
        this.protocol = protocol;
    }
}
